package logic

import (
	"encoding/csv"
	"fmt"
	"github.com/xuri/excelize/v2"
	"gvb-server/Request"
	"gvb-server/global"
	"gvb-server/models"
	"gvb-server/utils"
	"strconv"
	"strings"
	"time"
)

func (u User) GetUserList(s Request.UserRequest) (utils.RList[models.Users], *excelize.File, string, error) {
	var ad []models.Users
	var rb utils.RList[models.Users] // 注意这里

	//w := map[string]any{
	//	"status": 1,
	//}

	conditions := make([]string, 0)

	if s.Enable != "" {
		conditions = append(conditions, fmt.Sprintf("status = '%s'", s.Enable))
	}

	//conditions = append(conditions, fmt.Sprintf("username = '%s'", val))

	if s.Tel != "" {
		//w["tel"] = s.Tel
		conditions = append(conditions, fmt.Sprintf("tel = '%s'", s.Tel))
	}

	fmt.Println("=======================================")
	fmt.Println(s.CreateAt)

	if len(s.CreateAt) > 0 {
		fmt.Println("解析时间字符串:", s.CreateAt[0])

		t, err := time.Parse(time.RFC3339, s.CreateAt[0])
		t1, err := time.Parse(time.RFC3339, s.CreateAt[1])
		durationString := "23h59m59s"
		duration, err := time.ParseDuration(durationString)
		newTime := t1.Add(duration)
		unixTime := newTime.Unix()

		if err != nil {
			return rb, nil, "", err
		}

		conditions = append(conditions, fmt.Sprintf("create_date >= %v", t.Unix()))
		conditions = append(conditions, fmt.Sprintf("create_date <= %v", unixTime))
	}

	if s.NickName != "" {
		conditions = append(conditions, fmt.Sprintf("name LIKE '%%%s%%'", s.NickName))
	}

	// IN
	//if val := params.Get("id_in"); val != "" {
	//	idList := strings.Split(val, ",")
	//	conditions = append(conditions, fmt.Sprintf("id IN (%s)", strings.Join(idList, ",")))
	//}
	//
	//// OR
	//if val := params.Get("status_or"); val != "" {
	//	statusList := strings.Split(val, ",")
	//	orConditions := make([]string, len(statusList))
	//	for i, status := range statusList {
	//		orConditions[i] = fmt.Sprintf("status = %s", status)
	//	}
	//	conditions = append(conditions, "("+strings.Join(orConditions, " OR ")+")")
	//}

	// 构建完整的 SQL 查询语句
	//sqlQuery := "SELECT * FROM users"
	sqlQuery := ""
	if len(conditions) > 0 {
		sqlQuery = strings.Join(conditions, " AND ")
	}
	fmt.Printf("%v", sqlQuery)

	// 判断是否导出
	if s.Type == 1 {
		err = global.DB.Where(sqlQuery).Order("create_date desc").Find(&ad).Error
		// 1、 导出excel
		//exp, err2 := expUserList(ad)
		//if err2 != nil {
		//	return rb, exp, "", err2
		//}
		//return rb, exp, "", err2

		// 2、导出csv
		strExp, err3 := expUserCSVList(ad)
		return rb, nil, strExp, err3

	} else {
		// 获取总数
		global.DB.Model(models.Users{}).Where(sqlQuery).Count(&totalRows)
		if err != nil {
			return rb, nil, "", err
		}
		// 开始分页
		if totalRows%int64(s.Size) == 0 {
			totalPages = totalRows / int64(s.Size)
		} else {
			totalPages = (totalRows / int64(s.Size)) + 1
		}

		// 直接用find关联表
		err = global.DB.Limit(s.Size).Offset((s.Page - 1) * s.Size).Where(sqlQuery).Order("create_date desc").Find(&ad).Error

		// 循环 截取加密手机号 EncryptPhone
		//for _, users := range ad {
		//	users.Email = utils.EncryptEmail(users.Email)
		//	users.Tel = utils.EncryptPhone(users.Tel)
		//}
	}

	rb.List = ad
	rb.Page = s.Page
	rb.Size = s.Size
	rb.TotalRows = int(totalRows)
	rb.TotalPages = totalPages
	return rb, nil, "", err
}

// expUserCSVList 导出CSV
func expUserCSVList(data []models.Users) (string, error) {
	var b strings.Builder
	writer := csv.NewWriter(&b)
	// 写入标题行
	err = writer.Write([]string{"id", "nick_name", "user_name", "tel", "status", "create_date"})
	if err != nil {
		return "", err
	}
	// 写入数据
	for _, datum := range data {
		status := "禁用"
		if datum.Status == 1 {
			status = "启用"
		}
		strID := strconv.FormatUint(uint64(datum.ID), 10)
		strCreateDate := strconv.FormatUint(uint64(datum.CreateDate), 10)
		err = writer.Write([]string{
			strID,
			datum.NickName,
			datum.UserName,
			datum.Tel,
			status,
			strCreateDate,
		})
		if err != nil {
			return "", err
		}
	}
	writer.Flush()
	return b.String(), nil
}

// expUserList 导出excel
func expUserList(data []models.Users) (*excelize.File, error) {
	// 设置模版
	f := excelize.NewFile() // 新建一个.xlsx文件
	index, _ := f.NewSheet("Sheet1")
	f.SetActiveSheet(index)
	f.SetCellValue("Sheet1", "A1", "id") // 设置Sheet1中对应位置的值
	f.SetCellValue("Sheet1", "B1", "nick_name")
	f.SetCellValue("Sheet1", "C1", "user_name")
	f.SetCellValue("Sheet1", "D1", "tel")
	f.SetCellValue("Sheet1", "E1", "status")
	f.SetCellValue("Sheet1", "F1", "create_date")
	for i, datum := range data {
		status := "启用"
		if datum.Status == 1 {
			status = "启用"
		}
		f.SetCellValue("Sheet1", fmt.Sprintf("A%d", i+2), datum.ID)
		f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i+2), datum.NickName)
		f.SetCellValue("Sheet1", fmt.Sprintf("C%d", i+2), datum.UserName)
		f.SetCellValue("Sheet1", fmt.Sprintf("D%d", i+2), datum.Tel)
		f.SetCellValue("Sheet1", fmt.Sprintf("E%d", i+2), status)
		f.SetCellValue("Sheet1", fmt.Sprintf("F%d", i+2), datum.CreateDate)
	}
	return f, err
}

func (u User) UserLogin(l Request.UserLoginRequest) (Pub utils.Response) {
	Pub = utils.HandleToken(l.UserName, l.Password)
	return
}

func (u User) DelUser(s Request.UserDelRequest) (Pub utils.PubStatus) {

	models.UserDelByIds(s)
	Pub.Status = utils.SUCCESS
	Pub.Msg = "删除成功"
	return
}

// CreateUser 修改文件
func (u User) CreateUser(s Request.UserCreateRequest) (Pub utils.PubStatus) {
	if s.Password != s.RePassword {
		Pub.Msg = "俩次密码不一致！ 请重新输入"
		return
	}
	s.Password = utils.HashPassword([]byte(s.Password))
	Pub = models.UserCreateData(s)
	return
}

// Role 角色
type Role struct {
	Id       int    `json:"id"`
	Name     string `json:"name"`
	CreateDt int    `json:"create_dt"`
}

// Dpt 部门
type Dpt struct {
	Id       int    `json:"id"`
	Name     string `json:"name"`
	ParentId int    `json:"parent_id"`
	CreateDt int    `json:"create_dt"`
}

type UserInfo struct {
	Id           uint           `json:"id"`
	Name         string         `json:"name"`
	NickName     string         `json:"nick_name"`
	RoleId       uint           `json:"roleId"`
	DepartmentId uint           `json:"departmentId"`
	Tel          string         `json:"tel"`
	Email        string         `json:"email"`
	Imgs         []models.ImgSt `json:"imgs"`
	Role         Role           `json:"role"`
	Department   Dpt            `json:"department"`
	CreateDt     int64          `json:"create_dt"`
}

// GetUserInfoById 获取用户信息
func (u User) GetUserInfoById(id int) UserInfo {

	dpt := Dpt{
		Id:       1,
		Name:     "技术部",
		ParentId: 0,
		CreateDt: 1737095179171,
	}
	role := Role{
		Id:       1,
		Name:     "超级管理员",
		CreateDt: 1737095179171,
	}

	pics := models.GetUserImgs(id)

	info, _ := models.GetInfoById(id)

	fmt.Println("=========info==========")
	fmt.Println(info)
	info2 := UserInfo{
		Id:           info.ID,
		Name:         info.NickName,
		NickName:     info.UserName,
		Imgs:         pics, // 如果是私有域名 就需要再后面拼上token
		RoleId:       info.Role,
		Tel:          info.Tel,
		Email:        info.Email,
		DepartmentId: info.DepartId,
		Role:         role,
		Department:   dpt,
		CreateDt:     info.CreateDate,
	}

	//	私有七牛访问： e=10位时间戳 token=获取的token ，前面的域名是绑定的cdn域名，测试的七牛自带的有效期30天
	//http://srm41g70z.hd-bkt.clouddn.com/FlnA5J447Xg7r8j6FN9SFhBVsAHG?e=1739436696&token=Q4nDMT9_9zk3fybKmQGnGUlohf5EYqQdRidzTodi:b2HdhJ2ZwSa96iMG0ww8CULaZxw=

	return info2
}

// {
// "data": [{
// "id": 1,
// "name": "系统总揽",
// "type": 1,
// "url": "main/analysis",
// "icon": "e-icon-monitor",
// "sort": 106,
// "children": [{
// "id": 39,
// "name": "核心技术",
// "type": 2,
// "url": "main/analysis/overview",
// "parentId": 1,
// "sort": 101,
// "children": null
// }, {
// "id": 40,
// "name": "商品统计",
// "type": 2,
// "url": "main/analysis/dashboard",
// "parentId": 1,
// "sort": 102,
// "children": null
// }]
// }, {
// "id": 2,
// "name": "系统管理",
// "type": 1,
// "url": "main/system",
// "icon": "e-icon-setting",
// "sort": 103,
// "children": [{
// "id": 42,
// "name": "用户管理",
// "type": 2,
// "url": "main/system/user",
// "parentId": 2,
// "sort": 201,
// "children": [{
// "id": 43,
// "name": "创建用户",
// "type": 3,
// "permission": "system:user:create",
// "parentId": 42,
// "sort": 202,
// }, {
// "id": 44,
// "name": "删除用户",
// "type": 3,
// "permission": "system:user:del",
// "parentId": 42,
// "sort": 203,
// }, {
// "id": 45,
// "name": "修改用户",
// "type": 3,
// "permission": "system:user:edit",
// "parentId": 42,
// "sort": 204,
// }, {
// "id": 46,
// "name": "查询用户",
// "type": 3,
// "permission": "system:user:search",
// "parentId": 42,
// "sort": 205,
// }]
// }]
// }, {
// "id": 3,
// "name": "部门管理",
// "type": 2,
// "url": "main/system/detpartment",
// "sort": 300,
// "children": [{
// "id": 301,
// "name": "创建部门",
// "type": 3,
// "permission": "system:detpartment:create",
// "parentId": 42,
// "sort": 301,
// },
// [{
// "id": 302,
// "name": "删除部门",
// "type": 3,
// "url": "main/system/dti",
// "permission": "system:detpartment:del",
// "parentId": 42,
// "sort": 302,
// }],
// [{
// "id": 303,
// "name": "修改部门",
// "type": 3,
// "permission": "system:detpartment:edit",
// "parentId": 42,
// "sort": 303,
// }],
// [{
// "id": 304,
// "name": "查询部门",
// "type": 3,
// "permission": "system:detpartment:search",
// "parentId": 42,
// "sort": 304,
// }]
// ]
// }],
// {
// "id": 4,
// "name": "菜单管理",
// "type": 2,
// "url": "main/system/menu",
// "sort": 400,
// "children": [{
// "id": 401,
// "name": "创建部门",
// "type": 3,
// "permission": "system:menu:create",
// "parentId": 42,
// "sort": 401,
// },
// [{
// "id": 402,
// "name": "删除部门",
// "type": 3,
// "permission": "system:menu:del",
// "parentId": 42,
// "sort": 402,
// }],
// [{
// "id": 403,
// "name": "修改部门",
// "type": 3,
// "permission": "system:menu:edit",
// "parentId": 42,
// "sort": 403,
// }],
// [{
// "id": 404,
// "name": "查询部门",
// "type": 3,
// "permission": "system:menu:search",
// "parentId": 42,
// "sort": 404,
// }]
// ]
// }]
// }

// GetUserMenusById 获取用户
func (u User) GetUserMenusById(id int) []CTree {

	fmt.Printf("用户权限id: %v", id)

	//var TreeModels []TreeModel
	//// 方式一，未知长度下 追加进去
	//var TreeModels = make([]TreeModel, 0)
	//tree1 := TreeModel{
	//	Id:       1,
	//	Name:     "系统总揽",
	//	Url:      "main/analysis",
	//	Icon:     "e-icon-monitor",
	//	Type:     1,
	//	ParentId: 0,
	//	Sort:     102,
	//}
	////tree.....1233456xxxxxxx......
	//TreeModels = append(TreeModels,tree1)
	//

	// 方式二，必须知道长度
	var TreeModels = make([]CTree, 17)
	TreeModels[0].Id = 1
	TreeModels[0].Name = "系统总揽"
	TreeModels[0].Permission = ""
	TreeModels[0].Url = "/main/analysis"
	TreeModels[0].Icon = "el-icon-Monitor"
	TreeModels[0].Type = 1
	TreeModels[0].ParentId = 0
	TreeModels[0].Sort = 102

	TreeModels[1].Id = 39
	TreeModels[1].Name = "核心技术"
	TreeModels[1].Permission = ""
	TreeModels[1].Url = "/main/analysis/overview"
	TreeModels[1].Icon = ""
	TreeModels[1].Type = 2
	TreeModels[1].ParentId = 1
	TreeModels[1].Sort = 101

	TreeModels[2].Id = 40
	TreeModels[2].Name = "商品统计"
	TreeModels[2].Permission = ""
	TreeModels[2].Icon = ""
	TreeModels[2].Url = "/main/analysis/dashboard"
	TreeModels[2].Type = 2
	TreeModels[2].ParentId = 1
	TreeModels[2].Sort = 103

	TreeModels[3].Id = 2
	TreeModels[3].Name = "系统管理"
	TreeModels[3].Permission = ""
	TreeModels[3].Icon = "el-icon-Setting"
	TreeModels[3].Url = "/main/system"
	TreeModels[3].Type = 1
	TreeModels[3].ParentId = 0
	TreeModels[3].Sort = 200

	TreeModels[4].Id = 42
	TreeModels[4].Name = "用户管理"
	TreeModels[4].Permission = ""
	TreeModels[4].Icon = ""
	TreeModels[4].Url = "/main/system/user"
	TreeModels[4].Type = 1
	TreeModels[4].ParentId = 2
	TreeModels[4].Sort = 201

	TreeModels[5].Id = 43
	TreeModels[5].Name = "创建用户"
	TreeModels[5].Permission = "system:user:create"
	TreeModels[5].Icon = ""
	TreeModels[5].Url = ""
	TreeModels[5].Type = 3
	TreeModels[5].ParentId = 42
	TreeModels[5].Sort = 202

	TreeModels[6].Id = 44
	TreeModels[6].Name = "删除用户"
	TreeModels[6].Permission = "system:user:del"
	TreeModels[6].Icon = ""
	TreeModels[6].Url = ""
	TreeModels[6].Type = 3
	TreeModels[6].ParentId = 42
	TreeModels[6].Sort = 203

	TreeModels[7].Id = 45
	TreeModels[7].Name = "修改用户"
	TreeModels[7].Permission = "system:user:edit"
	TreeModels[7].Icon = ""
	TreeModels[7].Url = ""
	TreeModels[7].Type = 3
	TreeModels[7].ParentId = 42
	TreeModels[7].Sort = 204

	TreeModels[8].Id = 46
	TreeModels[8].Name = "查询用户"
	TreeModels[8].Permission = "system:user:search"
	TreeModels[8].Icon = ""
	TreeModels[8].Url = ""
	TreeModels[8].Type = 3
	TreeModels[8].ParentId = 42
	TreeModels[8].Sort = 205

	// -------------------------

	TreeModels[9].Id = 3
	TreeModels[9].Name = "部门管理"
	TreeModels[9].Url = "/main/system/detpartment"
	TreeModels[9].Icon = ""
	TreeModels[9].Type = 2
	TreeModels[9].ParentId = 2
	TreeModels[9].Sort = 300

	TreeModels[10].Id = 301
	TreeModels[10].Name = "创建部门"
	TreeModels[10].Permission = "system:department:create"
	TreeModels[10].Type = 3
	TreeModels[10].Url = ""
	TreeModels[10].Icon = ""
	TreeModels[10].ParentId = 3
	TreeModels[10].Sort = 301

	TreeModels[11].Id = 302
	TreeModels[11].Name = "删除部门"
	TreeModels[11].Permission = "system:department:del"
	TreeModels[11].Type = 3
	TreeModels[11].Url = ""
	TreeModels[11].Icon = ""
	TreeModels[11].ParentId = 3
	TreeModels[11].Sort = 302

	TreeModels[12].Id = 303
	TreeModels[12].Name = "修改部门"
	TreeModels[12].Permission = "system:department:edit"
	TreeModels[12].Type = 3
	TreeModels[12].Url = ""
	TreeModels[12].Icon = ""
	TreeModels[12].ParentId = 3
	TreeModels[12].Sort = 303

	TreeModels[13].Id = 304
	TreeModels[13].Name = "搜索部门"
	TreeModels[13].Permission = "system:department:search"
	TreeModels[13].Type = 3
	TreeModels[13].Url = ""
	TreeModels[13].Icon = ""
	TreeModels[13].ParentId = 3
	TreeModels[13].Sort = 304

	// -------------------------

	TreeModels[14].Id = 4
	TreeModels[14].Name = "随便聊聊"
	TreeModels[14].Url = "/main/story"
	TreeModels[14].Icon = "el-icon-Monitor"
	TreeModels[14].Type = 1
	TreeModels[14].ParentId = 0
	TreeModels[14].Sort = 400

	TreeModels[15].Id = 401
	TreeModels[15].Name = "你的故事"
	TreeModels[15].Url = "/main/story/chat"
	TreeModels[15].Icon = ""
	TreeModels[15].Type = 2
	TreeModels[15].ParentId = 4
	TreeModels[15].Sort = 401

	TreeModels[16].Id = 402
	TreeModels[16].Name = "故事列表"
	TreeModels[16].Url = "/main/story/list"
	TreeModels[16].Icon = ""
	TreeModels[16].Type = 2
	TreeModels[16].ParentId = 4
	TreeModels[16].Sort = 402
	fmt.Printf("Tree: %#v\n", TreeModels)
	return buildTree(TreeModels)
}

// CTree 分类树形结构
type CTree struct {
	Id         int64   `json:"id"`
	Name       string  `json:"name"`
	ParentId   int64   `json:"parent_id"`
	Type       int64   `json:"type"`
	Icon       string  `json:"icon"`
	Sort       int64   `json:"sort"`
	Url        string  `json:"url,omitempty"`
	Permission string  `json:"Permission,omitempty"`
	Children   []CTree `json:"children,omitempty"`
}

func buildTree(cates []CTree) []CTree {
	var rootNode []CTree
	for i := range cates {
		if cates[i].ParentId == 0 {
			cates[i].Children = buildChildren(cates, cates[i].Id)
			rootNode = append(rootNode, cates[i])
		}
	}
	return rootNode
}

// buildChecnTree 获取子类
func buildChildren(cates []CTree, parentId int64) []CTree {
	var children []CTree
	for i := range cates {
		if cates[i].ParentId == parentId {
			cates[i].Children = buildChildren(cates, cates[i].Id)
			children = append(children, cates[i])
		}
	}
	return children
}

func buildTree2(cates []CTree) []CTree {
	var CNode []CTree
	for _, v := range cates {
		if v.ParentId == 0 {
			//fmt.Printf("父类有；%#v\n", v)
			CNode = buildChecnTree2(cates, v)
			fmt.Printf("zi类有；%#v\n", CNode)

			nn := CTree{
				Id:         v.Id,
				ParentId:   v.ParentId,
				Permission: v.Permission,
				Type:       v.Type,
				Icon:       v.Icon,
				Sort:       v.Sort,
				Url:        v.Url,
				Name:       v.Name,
				Children:   CNode,
			}

			CNode = append(CNode, nn)
		}
	}
	fmt.Printf("所有的；%#v\n", CNode)
	return CNode
}

// buildChecnTree 获取子类
func buildChecnTree2(cates []CTree, cate CTree) []CTree {
	ChendNode := []CTree{}

	for _, children := range cates {
		if children.ParentId == cate.Id {
			cd := buildChecnTree2(cates, children)
			node := CTree{
				Id:         children.Id,
				ParentId:   children.ParentId,
				Permission: children.Permission,
				Type:       children.Type,
				Icon:       children.Icon,
				Sort:       children.Sort,
				Url:        children.Url,
				Name:       children.Name,
				Children:   cd,
			}
			ChendNode = append(ChendNode, node)
		}
	}
	return ChendNode
}

//func Tree() []CTree {
//	menus := []models.Menu{}
//
//	global.DB.Find(&menus)
//
//	fmt.Printf("所有可用菜单：%#v\n", menus)
//	res := buildTree(menus)
//	return res
//}

// public function getMenuTree(array $menus)
// {
// 	$data = [];
// 	foreach ($menus as $menu) {
// 		if ($menu['pid'] === 0) {
// 			$data[] = $this->getChildren($menus, $menu);
// 		}
// 	}

// 	return $data;
// }

// public function getChildren($menus, $menu)
// {
// 	$c = [];
// 	foreach ($menus as $children) {
// 		if ($menu['id'] === $children['pid']) {
// 			$c[] = $this->getChildren($menus, $children);
// 		}
// 	}
// 	$menu['children'] = $c;
// 	$menu['api'] = $this->formatApi($menu['api']);

//		return $menu;
//	}
